This example shows how to fit an arbitrary function to your data

imports


In [1]:
%matplotlib inline
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

your function


In [2]:
def fit_func(x, a, b):
    return a*x + b

data


In [3]:
x = np.array([1, 2, 3, 9])
y = np.array([1, 1.5, 2, 3])

fitting


In [4]:
params = curve_fit(fit_func, x, y)

results - parameters


In [5]:
[a, b] = params[0]
print ('a:',a,'\tb:',b)


a: 0.229032258063 	b: 1.01612903226

results - errors


In [6]:
pcov=params[1]
[da,db] = np.sqrt(np.diag(pcov))
print ('err a:',da,'\terr b:',db)


err a: 0.0446980850234 	err b: 0.21783152214

plot data and fit


In [7]:
x_new = np.linspace(x[0], x[-1], 50)
y_new = fit_func(x_new, a, b)

plt.plot(x,y,'o')
plt.plot(x_new, y_new,'-')
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.ylim([y[0]-1, y[-1] + 1 ])
plt.show()



In [ ]: